package com.tf_cut.backend.agent.mobile.controller;

import com.tf_cut.backend.agent.mobile.vo.AgentProfitVo;
import com.tf_cut.backend.agent.service.*;
import com.tf_cut.backend.agent.statistics.service.AgentCommissionService;
import com.tf_cut.backend.agent.statistics.vo.AgentCommissionVo;
import com.tf_cut.backend.agent.vo.*;
import com.tf_cut.backend.common.pojo.Result;
import com.tf_cut.backend.util.ConfigSettingUtil;
import com.tf_cut.backend.util.SendMail;
import com.tf_cut.backend.util.SerialNoUtil;
import com.tf_cut.backend.util.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/backend/agent/mobile/cash")
public class AgentMobileCashController {

    @Autowired
    private AgentCashOrderService agentCashOrderService;

    @Autowired
    private SerialNoUtil serialNoUtil;

    @Autowired
    private AgentAccountService agentAccountService;

    @Autowired
    private TInputBankCodeService tInputBankCodeService;

    @Autowired
    private AgentAccountBankService agentAccountBankService;

    @Autowired
    private AgentCommissionService agentCommissionService;

    @Autowired
    private  AgentAndAccountService agentAndAccountService;

    @Autowired
    private ConfigSettingUtil configSettingUtil;

    @Autowired
    private AgentService agentService;

    @Autowired
    private SendMail sendMail;

    @GetMapping("/withdrawallist")
    public  Result<List<AgentCashOrderVo>> withdrawallist(@RequestParam String agentId,@RequestParam String startDate,@RequestParam String endDate) {
        Result<List<AgentCashOrderVo>> cashOrderResult=null;

        try {
            //获取aggentaccountId
            AgentAndAccountVo agentAndAccountVo = agentAccountService.findAgentAccountIdWithAgentId(agentId);

            if(null!=agentAndAccountVo){
                List<AgentCashOrderVo> agentCashOrderVos = agentCashOrderService.findlistCashOrderpage(AgentCashOrderVo.builder()
                        .agentAccountId(agentAndAccountVo.getAgentAccountId())
                        .startDate(startDate).endDate(endDate).build());
                cashOrderResult=Result.of(agentCashOrderVos);

            }else{
                log.error("没有虚拟账号");
                cashOrderResult=Result.of(new ArrayList<AgentCashOrderVo>(),true,"没有虚拟账号");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            cashOrderResult = Result.of(new ArrayList<AgentCashOrderVo>());
            cashOrderResult.setMsg(e.getMessage());
            cashOrderResult.setFlag(false);

        }

        return cashOrderResult;

    }

    @PostMapping("/withdrawalApply")
    public  Result<AgentCashOrderVo> withdrawalApply(@RequestBody AgentCashOrderVo agentCashOrder) {
        Result<AgentCashOrderVo> cashOrderResult=null;

        try {
            agentCashOrder.setOrderId(serialNoUtil.genSerialNo("T","X",agentCashOrder.getOrderId()));
            agentCashOrder.setOrderCode(agentCashOrderService.getTXSerialNo());

            AgentAndAccountVo agentAndAccountVo = agentAccountService.findAgentAccountIdWithAgentId(agentCashOrder.getAgentId());

            if(null!=agentAndAccountVo){
                agentCashOrder.setAgentAccountId(agentAndAccountVo.getAgentAccountId());
            }


            if(agentAndAccountVo.getAgentType()!=null){
                if(agentAndAccountVo.getAgentType()==0){//个人===》计算个税
                    List<String> list=configSettingUtil.getConfigValuesList("WITHDRAWAL_RATE");
                    if(list.size()>0){
                        Double rate=Double.parseDouble(list.get(0));
                        agentCashOrder.setTheTaxPayableAmount(agentCashOrder.getCashAmount().multiply(BigDecimal.valueOf(rate)));
                        agentCashOrder.setTheAmount(agentCashOrder.getCashAmount().subtract(agentCashOrder.getTheTaxPayableAmount()));

                    }else{
                        return Result.of(null,false,"未设置个税规则，请与管理员联系");
                    }
                }else if(agentAndAccountVo.getAgentType()==1){//企业==》不计算个税
                    agentCashOrder.setTheTaxPayableAmount(BigDecimal.valueOf(0));
                    agentCashOrder.setTheAmount(agentCashOrder.getCashAmount());
                }
            }else{
                return Result.of(null,false,"版本更新，请联系管理员对当前代理商进行代理商类型设置。");
            }

            agentCashOrder.setApplyTime(new Date());
            agentCashOrder.setOrderType(0);
            //提现申请则扣除余额: 这里要同时成功！
            this.agentCashOrderService.save(agentCashOrder);
            this.agentCashOrderService.update(agentCashOrder);
            /* TODO 发送邮件*/
            sendMail.withdrawInfoMailSend(agentCashOrder);
            cashOrderResult = Result.of(agentCashOrder);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
            cashOrderResult = Result.of(new AgentCashOrderVo());
            cashOrderResult.setMsg(e.getMessage());
            cashOrderResult.setFlag(false);

        }

        return cashOrderResult;

    }



    /**
     * 查询银行bankcode
     * @return
     */
    @GetMapping("/bankcodelist")
    public  Result<List<TInputBankCodeVo>> bankcodelist(){

        Result<List<TInputBankCodeVo>> result=null;
        try {

            result = this.tInputBankCodeService.list(TInputBankCodeVo.builder().build());


        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(new ArrayList<TInputBankCodeVo>());
            result.setMsg(e.getMessage());
            result.setFlag(false);

        }

        return result;

    }


    /**
     * 查询所属账号
     * @return
     */
    @GetMapping("/accountBankList")
    public  Result<List<AgentAccountBankVo>> accountBankList(@RequestParam String agentId){

        Result<List<AgentAccountBankVo>> result=null;
        try {
            AgentAndAccountVo agentAndAccountVo = agentAccountService.findAgentAccountIdWithAgentId(agentId);

            if(null!=agentAndAccountVo){
                result = this.agentAccountBankService.list(AgentAccountBankVo.builder()
                        .agentAccountId(agentAndAccountVo.getAgentAccountId())
                        .delFlag("Y").build());
            }



        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(new ArrayList<AgentAccountBankVo>());
            result.setMsg(e.getMessage());
            result.setFlag(false);

        }

        return result;

    }

    /**
     * 添加银行卡
     * @param agentAccountBankVo
     * @return
     */
    @PostMapping("/insertAccountBank")
    public  Result<AgentAccountBankVo> insertAccountBank(@RequestBody AgentAccountBankVo agentAccountBankVo) {
        Result<AgentAccountBankVo> cashOrderResult=null;

        try {
            agentAccountBankVo.setAgentBankId(UUIDUtil.getUUID());

            AgentAndAccountVo agentAndAccountVo = agentAccountService.findAgentAccountIdWithAgentId(agentAccountBankVo.getAgentId());

            if(null!=agentAndAccountVo){
                agentAccountBankVo.setAgentAccountId(agentAndAccountVo.getAgentAccountId());
            }
            agentAccountBankVo.setCreateTime(new Date());
            agentAccountBankVo.setDelFlag("Y");

            this.agentAccountBankService.save(agentAccountBankVo);

            cashOrderResult = Result.of(agentAccountBankVo);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            cashOrderResult = Result.of(AgentAccountBankVo.builder().build());
            cashOrderResult.setMsg(e.getMessage());
            cashOrderResult.setFlag(false);

        }

        return cashOrderResult;

    }


    /**
     * 查询收益
     * @return
     */
    @GetMapping("/agentCommionInfo")
    public  Result<AgentProfitVo> agentCommionInfo(@RequestParam String agentId){

        Result<AgentProfitVo> result=null;
        try {

            //查询
            AgentAndAccountVo agentAndAccountVo = agentAccountService.findAgentAccountIdWithAgentId(agentId);
            //月结分润
            AgentCommissionVo monthcommissionWithAgent = this.agentCommissionService.findCommissionWithAgent(AgentCommissionVo.builder()
                    .agentAccountId(agentAndAccountVo.getAgentAccountId())
                    .paySubject("0004").build());
            AgentCommissionVo seamcommissionWithAgent = this.agentCommissionService.findCommissionWithAgent(AgentCommissionVo.builder()
                    .agentAccountId(agentAndAccountVo.getAgentAccountId())
                    .paySubject("0005").build());


            //本月收益

            //本月第一天和最后一天
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MONTH, 0);
            c.set(Calendar.DAY_OF_MONTH,1);//1:本月第一天
            String startDate= format.format(c.getTime());
            Calendar ca = Calendar.getInstance();
            ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
            String endDate= format.format(ca.getTime());


            AgentCommissionVo month = this.agentCommissionService.findCommissionWithAgent(AgentCommissionVo.builder()
                    .agentAccountId(agentAndAccountVo.getAgentAccountId()).startDatestring(startDate)
                    .endDatesring(endDate)
                    .paySubject("0004").build());
            AgentCommissionVo seam = this.agentCommissionService.findCommissionWithAgent(AgentCommissionVo.builder()
                    .agentAccountId(agentAndAccountVo.getAgentAccountId()).startDatestring(startDate)
                    .endDatesring(endDate)
                    .paySubject("0005").build());

            AgentProfitVo.AgentProfitVoBuilder bulider = AgentProfitVo.builder();
            bulider.agentAccountBalance(agentAndAccountVo.getAgentAccountBalance())
                    .agentAccountIncome(agentAndAccountVo.getAgentAccountIncome())
                    .agentAccountPay(agentAndAccountVo.getAgentAccountPay())
                    .monthCommission(monthcommissionWithAgent.getStepAmount())
                    .monthProfit(month.getStepAmount().add(seam.getStepAmount()))
                    .seasonCommission(seamcommissionWithAgent.getStepAmount());

            //查询
            result=Result.of(bulider.build());



        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(AgentProfitVo.builder().build());
            result.setMsg(e.getMessage());
            result.setFlag(false);

        }

        return result;

    }

    /**
     * 查询季结和月结
     * @return
     */
    @GetMapping("/findCommionInfolist")
    public  Result<List<AgentCommissionVo>> findCommionInfolist(@RequestParam String agentId,@RequestParam String startDate,@RequestParam String endDate,@RequestParam String paySubject){

        Result<List<AgentCommissionVo>> result=null;
        try {

//            AgentAndAccountVo data = this.agentService.get(agentId).getData();
//            List<String> agentIds=new ArrayList<>();
//            agentIds.add(data.getAgentId());
//            //如果等于0 代表一级代理商
//            if(data.getParentAgentId().equals("0")) {
//                List<AgentAndAccountVo> data1 = this.agentService.list(AgentAndAccountVo.builder()
//                        .parentAgentId(data.getAgentId()).build()).getData();
//                if (data1.size() > 0) {
//                    agentIds.addAll(data1.stream().map(e -> e.getAgentId()).collect(Collectors.toList()));
//                }
//            }
//
//            //查询
//            List<AgentAndAccountVo> agentAccountwithagentIds = agentAndAccountService.findAgentAccountwithagentIds(agentIds);
//            List<String> agentAccountIds = agentAccountwithagentIds.stream().map(e -> e.getAgentAccountId()).collect(Collectors.toList());
            List<String> agentIds=new ArrayList<>();
            agentIds.add(agentId);
            List<AgentAndAccountVo> agentAccountwithagentIds = agentAndAccountService.findAgentAccountwithagentIds(agentIds);

            List<AgentCommissionVo> rs = this.agentCommissionService.findCommission(AgentCommissionVo.builder()
                    .agentAccountId(agentAccountwithagentIds.get(0).getAgentAccountId())
                    .startDatestring(startDate)
                    .endDatesring(endDate)
                    .paySubject(paySubject)
                    .build());
            //查询
            result=Result.of(rs);



        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(null);
            result.setMsg(e.getMessage());
            result.setFlag(false);

        }

        return result;


    }


    /**
     * 查询累积收入支出明细
     * @return
     */
    @GetMapping("/findProfitlist")
    public  Result<List<AgentAccountDetailVo>> findProfitlist(@RequestParam String agentId,@RequestParam Integer operType,
                                                              @RequestParam String startDate,@RequestParam String endDate){



        Result<List<AgentAccountDetailVo>> result=null;
        try {

//            AgentAndAccountVo data = this.agentService.get(agentId).getData();
//            List<String> agentIds=new ArrayList<>();
//            agentIds.add(data.getAgentId());
//            //如果等于0 代表一级代理商
//            if(data.getParentAgentId().equals("0")) {
//                List<AgentAndAccountVo> data1 = this.agentService.list(AgentAndAccountVo.builder()
//                        .parentAgentId(data.getAgentId()).build()).getData();
//                if (data1.size() > 0) {
//                    agentIds.addAll(data1.stream().map(e -> e.getAgentId()).collect(Collectors.toList()));
//                }
//            }
//
//            //查询
//            List<AgentAndAccountVo> agentAccountwithagentIds = agentAndAccountService.findAgentAccountwithagentIds(agentIds);
//            List<String> agentAccountIds = agentAccountwithagentIds.stream().map(e -> e.getAgentAccountId()).collect(Collectors.toList());
            List<String> agentIds=new ArrayList<>();
            agentIds.add(agentId);
            List<AgentAndAccountVo> agentAccountwithagentIds = agentAndAccountService.findAgentAccountwithagentIds(agentIds);

            List<AgentAccountDetailVo> agentAccountDetailNoPage = this.agentAndAccountService.findAgentAccountDetailNoPage(AgentAccountDetailVo.builder()
                    .agentAccountId(agentAccountwithagentIds.get(0).getAgentAccountId())
//                    .agentAccountIds(agentAccountIds)
                    .startDate(startDate)
                    .endDate(endDate)
                    .operType(operType)
                    .build());

                result=Result.of(agentAccountDetailNoPage);

        } catch (Exception e) {
            log.error(e.getMessage(),e);
            result = Result.of(null);
            result.setMsg(e.getMessage());
            result.setFlag(false);

        }

        return result;

    }


}
